<template>
    <div class="page-header">
      <div class="search-section">
        <el-input 
          v-model="filterText" 
          placeholder="请输入配置名称进行搜索" 
          clearable
          class="search-input"
          @input="handleSearchInput"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="action-section">
        <el-button
          v-if="setButton"
          type="warning"
          class="action-btn"
          @click="handleClose"
        >
          <el-icon><Close /></el-icon>关闭窗口
        </el-button>
        <el-button
          v-if="setButton"
          type="primary"
          class="action-btn primary-btn"
          @click="handelSettingDlg"
        >
          <el-icon><Check /></el-icon>确认选择
        </el-button>
        <el-button
          v-else
          type="primary"
          class="action-btn primary-btn"
          @click="popup('add')"
        >
          <el-icon><Plus /></el-icon>新增预设
        </el-button>
      </div>
    </div>
  <el-scrollbar height="calc(100vh - 150px)">
    <div class="table-container">
	    <el-table 
        ref="table" 
        highlight-current-row 
        :data="presettingList" 
        class="custom-table"
        size="default" 
        border 
        empty-text="暂无数据" 
        @selection-change="selectSetChange"
        stripe
      >
        <el-table-column  type="selection" ></el-table-column>
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="配置名称"  align="center" width="250"></el-table-column>
        <el-table-column prop="taskType" label="任务类型"  width="120" align="center">
          <template #default="scope">
            <el-tag effect="dark" v-if="scope.row.taskType==='10'">{{ taskTypeMap[scope.row.taskType] || scope.row.taskType }}</el-tag>
            <el-tag v-else type="success" effect="dark">{{ taskTypeMap[scope.row.taskType] || scope.row.taskType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="logMode" label="日志模式" align="center" width="200">
          <template #default="scope">
            <span>{{ logModeMap[scope.row.logMode] || scope.row.logMode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="control" label="控制模式" align="center" width="150">
          <template #default="scope">
            <span>{{ controlMap[scope.row.control] || scope.row.control }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="distributed_mode" label="运行模式" align="center" width="150">
          <template #default="scope">
            <el-tag :type="scope.row.distributed_mode === 'distributed' ? 'warning' : 'info'" effect="dark">
              {{ distributedModeMap[scope.row.distributed_mode] || scope.row.distributed_mode }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pressureMode" label="压测模式" align="center" width="150">
          <template #default="scope">
            <span>{{ pressureModeMap[scope.row.pressureMode] || scope.row.pressureMode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="master_server" label="主服务机" align="center" width="300">
          <template #default="scope">
            <span v-if="scope.row.distributed_mode === 'distributed' && scope.row.master_server">{{ getServerName(scope.row.master_server) }}</span>
            <span v-else-if="scope.row.distributed_mode === 'distributed'" style="color: #909399;">默认</span>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="worker_servers" label="工作机" align="center" width="200">
          <template #default="scope">
            <div v-if="scope.row.distributed_mode === 'distributed'">
              <el-tag v-if="scope.row.worker_servers && scope.row.worker_servers.length > 0" v-for="item in scope.row.worker_servers" :key="item" type="info" style="margin-right: 5px">{{ getServerName(item) }}</el-tag>
              <span v-else style="color: #909399;">默认</span>
            </div>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="timeUnit" label="时长单位" align="center" >
          <template #default="scope">
            <span>{{ timeUnitMap[scope.row.timeUnit] || scope.row.timeUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人"  align="center" width="150"></el-table-column>
        <el-table-column label="创建时间"  align="center" width="170">
          <template #default="scope">
            {{ $tools.rTime(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column v-if="setButton === false" label=""  align="center" width="280px" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button @click="copyPresetting(scope.row)" type="warning" size="small" class="action-btn-small">
                <el-icon><CopyDocument /></el-icon>复制
              </el-button>
              <el-button @click='popup("edit",scope.row)' type="primary" size="small" class="action-btn-small">
                <el-icon><EditPen /></el-icon>编辑
              </el-button>
              <el-button @click="delPresetting(scope.row.id)" type="danger" size="small" class="action-btn-small">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination  
        background 
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="currentPages"
        @size-change="handleSizeChange"
        :page-sizes="[20, 50, 100, 200]"
        :default-page-size="50"
        :total="pages.count"
        :current-page="pages.current"
        next-text="下一页" 
        prev-text="上一页"
        class="custom-pagination"
      >
      </el-pagination>
    </div>
  </el-scrollbar>
  <!--  弹窗-->
  <el-dialog :title="dialogTitle" v-model="dialogVisible"  :before-close="closeDialog" top="40px" destroy-on-close custom-class="class_dialog">
    <div class="system-icon-content">
        <el-form :model="configForm"  :rules="rulesConfig" ref="ConfigRef" label-width="95px" >
            <div class="form-container">
              <el-scrollbar height="calc(100vh - 250px)">
                <div class="form-column">
                <el-form-item label="任务类型：" prop="taskType">
                  <el-radio-group v-model="selectTaskType">
                    <el-radio  label="10">
                      普通任务
                    </el-radio>
                    <el-radio  label="20">
                      定时任务
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item prop="name" label="配置名称：" >
                  <el-input v-model="configForm.name" placeholder="请输入配置名称"></el-input>
                </el-form-item>
                <el-form-item v-if="configForm.taskType==='20'" label="时间配置：" prop="rule">
                  <el-popover
                    v-model:visible="cronVisible"
                    placement="bottom-start"
                    width="650"
                    :teleported="true"
                    trigger="manual">
                    <template #reference>
                      <el-input
                        v-model="configForm.rule"
                        clearable
                        readonly
                        placeholder="请选择定时任务时间配置"
                        @click="cronFun"
                      />
                    </template>
                    <timerTaskCron
                      :runTimeStr="configForm.rule"
                      @closeTime="closeRunTimeCron"
                      @runTime="runTimeCron"
                    >
                      </timerTaskCron>
                  </el-popover>
                </el-form-item>
                <el-form-item prop="logMode" label="日志模式：" >
                  <el-select  v-model="selectedLogMode" placeholder="请选择日志模式" style="width: 100%">
                    <el-option label="关闭" value=0></el-option>
                    <el-option label="开启-全部日志" value=10></el-option>
                    <el-option label="开启-仅成功日志" value=20></el-option>
                    <el-option label="开启-仅失败日志" value=30></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="控制模式：" prop="control">
                  <el-select v-model="selectControlMode" placeholder="请选择控制模式" style="width: 100%">
                    <el-option label="集合模式" value=10></el-option>
                    <el-option label="单独模式" value=20></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="压测模式：" prop="pressureMode">
                  <el-select v-model="selectPressureMode" placeholder="请选择压测模式" style="width: 100%">
                    <el-option label="并发模式" value='10'></el-option>
                    <el-option label="阶梯模式" value='20'></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="时长单位：" prop="pressureMode">
                  <el-select v-model="configForm.timeUnit" placeholder="请选择时长单位" style="width: 100%">
                    <el-option label="s" value="s"></el-option>
                    <el-option label="m" value="m"></el-option>
                    <el-option label="h" value="h"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="思考时间：" prop="thinkTime">
                  <el-select v-model="selectTimeType" placeholder="请选择时间类型" style="width: 30%">
                    <el-option label="固定" value='10'></el-option>
                    <el-option label="随机" value='20'></el-option>
                  </el-select>
                  <span style="margin-top: 20px;margin-left: -10px;" v-if="configForm.thinkTimeType === '20'">
                    <el-input-number
                      v-model="configForm.thinkTime[0]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px;margin-left: 10px"
                    />
                    <span style="margin-right: 5px;margin-left: 5px">-</span>
                    <el-input-number
                      v-model="configForm.thinkTime[1]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px"
                    />
                  </span>
                  <span v-else>
                    <el-input-number
                      v-model="configForm.thinkTime[0]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px;margin-left: 10px"
                    />
                  </span>
                </el-form-item>
                <el-card v-if="configForm.pressureMode==='10'" style="background-color: #f5f7f9" class="card" shadow="always">
                  <el-form label-width="120px" :model="FormConcurrency"  :rules="rulesConcurrencyMode" ref="CaseRef">
                    <el-form-item label="并发用户数：" prop="concurrencyNumber">
                      <el-input v-model="FormConcurrency.concurrencyNumber"></el-input>
                    </el-form-item>
                    <el-form-item label="并发数步长：" prop="concurrencyStep">
                      <el-input v-model="FormConcurrency.concurrencyStep"></el-input>
                    </el-form-item>
                    <el-form-item label="持续时长：" prop="lastLong">
                      <el-input v-model="FormConcurrency.lastLong"></el-input>
                    </el-form-item>

                  </el-form>
                </el-card>
                <el-card v-if="configForm.pressureMode==='20'" style="margin-left: 7px;margin-right: 4px;background-color: #f5f7f9" class="card" shadow="always">
                  <el-form label-width="125px" :model="FormLadder" :rules="rulesLadderMode" ref="CaseRef">
                    <div v-for="(ladder, index) in FormLadder.ladders" :key="index">
                      <div style="color: #606266; display: flex; align-items: center; justify-content: space-between;">
                        <span>阶梯{{ index + 1 }}</span>
                        <el-button
                          :disabled="index < 1"
                          size="mini"
                          type="text"
                          @click="removeLadder(index)"
                        >
                          删除
                        </el-button>
                      </div>
                      <el-form-item label="并发用户数：" :prop="'ladders.' + index + '.concurrencyNumber'">
                        <el-input v-model="ladder.concurrencyNumber"></el-input>
                      </el-form-item>
                      <el-form-item label="并发数步长：" :prop="'ladders.' + index + '.concurrencyStep'">
                        <el-input v-model="ladder.concurrencyStep"></el-input>
                      </el-form-item>
                      <el-form-item label="阶梯持续时长：" :prop="'ladders.' + index + '.lastLong'">
                        <el-input v-model="ladder.lastLong"></el-input>
                      </el-form-item>
                    </div>
                  </el-form>
                  <el-button  style="width: 100%;margin-top: 20px; background-color: #ecf5ff; color: #409eff;" @click="addLadder" >
                    add Data
                  </el-button>
                </el-card>
              </div>
              </el-scrollbar>
              <div class="form-column">
                <el-form-item label="运行模式：" prop="distributed_mode">
                  <el-radio-group v-model="configForm.distributed_mode" @change="onDistributedModeChange">
                    <el-radio label="single">单机模式</el-radio>
                    <el-radio label="distributed">分布式模式</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="configForm.distributed_mode === 'distributed'" label="运行机器：" prop="resource">
                  <el-radio-group v-model="configForm.resource" @change="onResourceChange">
                    <el-radio label="10">默认
                      <el-tooltip content="使用机器管理中默认机器运行" :enterable="false" placement="top">
                        <el-icon><QuestionFilled /></el-icon>
                      </el-tooltip>
                    </el-radio>
                    <el-radio label="20">自定义
                      <el-tooltip content="手动选择主服务器和工作服务器" :enterable="false" placement="top">
                        <el-icon><QuestionFilled /></el-icon>
                      </el-tooltip>
                    </el-radio>
                  </el-radio-group>
                  <div v-if="configForm.resource === '20'" class="tip-box warning" style="margin-top: 5px;">
                    <el-icon><InfoFilled /></el-icon>
                    <span>请手动选择主服务器和工作服务器，确保资源可用。</span>
                  </div>
                </el-form-item>
                <!-- 自定义服务器选择 -->
                <div v-if="configForm.distributed_mode === 'distributed' && configForm.resource === '20'">
                  <el-form-item label="主服务机：" prop="master_server">
                    <el-select v-model="configForm.master_server" placeholder="请选择主服务器" style="width: 100%">
                      <el-option v-for="server in serverData" :key="server.id" :label="`${server.name} (${server.host_ip})`" :value="server.id" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="工作机：" prop="worker_servers">
                    <el-select v-model="configForm.worker_servers" multiple placeholder="请选择工作服务器" style="width: 100%">
                      <el-option v-for="server in serverData" :key="server.id" :label="`${server.name} (${server.host_ip})`" :value="server.id" />
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </div>
          </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button @click="closeDialog" >取 消</el-button>
          <el-button v-if="dialogTitle === '添加预设'" type="primary" @click="clickAdd" >保 存</el-button>
          <el-button v-if="dialogTitle === '编辑预设'" type="primary" @click="clickUpdate" >保 存</el-button>
      </div>
    </div>
  </el-dialog>

</template>

<script>
import timerTaskCron from "@/components/common/timerTaskCron";
import {mapMutations, mapState} from "vuex";
import { Close, Check, Plus, CopyDocument, EditPen, Delete, QuestionFilled, InfoFilled, Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  props: {
    setButton: {
      type: Boolean,
      default: false
    },
    taskType: {
      type: String
    },
    distributedMode: {
      type: String,
      default: 'single'
    }
  },
  computed: {
    ...mapState({
      server: state => state.server,
      pro: state => state.pro
    }),
    username() {
			return window.sessionStorage.getItem('username');
		},
    selectedLogMode: {
      get() {
        return this.configForm.logMode.toString();
      },
      set(value) {
        this.configForm.logMode = Number(value);
      }
    },
    selectPressureMode: {
      get() {
        return this.configForm.pressureMode.toString();
      },
      set(value) {
        this.configForm.pressureMode = value;
      }
     },
    selectControlMode: {
      get() {
        return this.configForm.control.toString();
      },
      set(value) {
        this.configForm.control = Number(value);
      }
     },
    selectTaskType: {
      get() {
        return this.configForm.taskType.toString();
      },
      set(value) {
        this.configForm.taskType = value;
      }
    },
    selectTimeType: {
      get() {
        return this.configForm.thinkTimeType.toString();
      },
      set(value) {
        this.configForm.thinkTimeType = value;
      }
     },

  },
  components: {
	  timerTaskCron,
    Close,
    Check,
    Plus,
    CopyDocument,
    EditPen,
    Delete,
    QuestionFilled,
    InfoFilled,
    Search
  },
  watch: {
    setButton(newVal) {
      if (newVal === true) {
        this.getPresetting(1); // 触发查询
      }
    },
    'configForm.thinkTimeType'(newType) {
      if (newType === '20') {
        this.configForm.thinkTime = [this.configForm.thinkTime[0], this.configForm.thinkTime[1]];
      } else {
        this.configForm.thinkTime = [this.configForm.thinkTime[0]];
      }

    }

  },

  data() {
    return {
        // 状态码映射
        taskTypeMap: {'10': '普通任务', '20': '定时任务'},
        logModeMap: {'0':'关闭','10': '开启-全部日志', '20': '开启-仅成功日志', '30': '开启-仅失败日志'},
        pressureModeMap: {'10': '并发模式', '20': '阶梯模式'},
        timeUnitMap: {'s': '秒', 'm': '分钟', 'h': '小时'},
        controlMap: {'10': '集合模式', '20': '单独模式'},
        distributedModeMap: {'distributed': '分布式模式', 'single': '单机模式'},

        SettingDlg: false,
        cronVisible: false,
        dialogVisible:false,
        importSetData: '',
        filterText:'',
        dialogType: '', // 对话框类型，用于区分不同类型的对话框
        dialogTitle: '', // 对话框标题，根据不同类型动态设置
        presettingList: [],
        serverData: [],
        configForm: {
        name:'',
        rule:'',
        taskType: '10',
        logMode: '0',
        pressureMode: '10',
        timeUnit: 's',
        control:'20',
        resource: '10',
        pressureConfig:{},
        project: '',
        creator:'',
        thinkTimeType:'10',
        thinkTime:[0],
        master_server: null,
        worker_servers: [],
        distributed_mode: 'single',
      },
      FormConcurrency:{
          lastLong:'',
          concurrencyNumber:'',
          concurrencyStep:''
        },
      FormLadder: {
        ladders: [
          { concurrencyNumber: '', concurrencyStep: '', lastLong: '' }
        ]
      },

        pages: {
          count: 0,
          current: 1
        },
        searchTimer: null,
        rulesConfig: {
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          thinkTime: [{ required: true, message: '请输入思考时间', trigger: 'blur' }],
          master_server: [
            { 
              validator: (rule, value, callback) => {
                if (this.configForm.distributed_mode === 'distributed' && this.configForm.resource === '20') {
                  if (!value) {
                    callback(new Error('请选择主服务器'));
                  } else if (this.configForm.worker_servers && this.configForm.worker_servers.includes(value)) {
                    callback(new Error('主服务器和工作服务器不能选择同一个'));
                  }
                }
                callback();
              }, 
              trigger: 'change' 
            }
          ],
          worker_servers: [
            { 
              validator: (rule, value, callback) => {
                if (this.configForm.distributed_mode === 'distributed' && this.configForm.resource === '20') {
                  if (!value || value.length === 0) {
                    callback(new Error('请选择工作服务器'));
                  } else if (this.configForm.master_server && value.includes(this.configForm.master_server)) {
                    callback(new Error('主服务器和工作服务器不能选择同一个'));
                  }
                }
                callback();
              }, 
              trigger: 'change' 
            }
          ]
        },
        rulesConcurrencyMode: {
          lastLong: [{ required: true, message: '请输入持续时长', trigger: 'blur' }],
          concurrencyNumber: [{ required: true, message: '请输入并发数', trigger: 'blur' }],
          concurrencyStep: [{ required: true, message: '请输入步长', trigger: 'blur' }]
        },
        rulesLadderMode: {},
    }
  },
  methods: {
    currentPages(currentPage) {
      this.getPresetting(1)
      this.pages.current = currentPage
    },

    handleSizeChange(size) {
      this.pages.pageSize = size;
      this.getPresetting(1);
    },

    // 防抖搜索
    handleSearchInput() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      this.searchTimer = setTimeout(() => {
        this.getPresetting(1, this.filterText);
      }, 500);
    },

    cronFun() {
     this.cronVisible = true;
    },

    closeRunTimeCron(isClose) {
      this.cronVisible = isClose;
    },

    runTimeCron(cron) {
      this.configForm.rule= cron;
    },

    async getPresetting(page,name) {
     const response =await this.$api.getPresetting({
       project_id: this.pro.id,
       isSetting: false,
       page: page,
       name: name,
       taskType:this.taskType,
       distributed_mode: this.distributedMode
     })
     if (response.status ===200){
				this.presettingList = response.data.result;
				this.pages = response.data;

			}
    },

    selectSetChange(selection) {
      if (selection.length > 1) {
        // 如果选择了多个项，取消选中所有之前的选项
        this.$refs.table.clearSelection();
        // 只保留最后一个选择的项
        this.$refs.table.toggleRowSelection(selection[selection.length - 1], true);
        this.importSetData = selection[selection.length - 1] || null;
      } else if (selection.length === 1) {
        this.importSetData = selection[0] || null;
      } else {
        this.importSetData = null;
      }
      console.log('importSetData', this.importSetData);
    },


    delPresetting(id) {
      ElMessageBox.confirm('此操作将永久删除该设置, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const response = await this.$api.delPresetting(id)
          if(response.status ===204){
            ElMessage({
              type: 'success',
              message: '删除成功!'
            });
            // 刷新页面
            this.getPresetting(1);
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    dataSubmit() {
      const params = {...this.configForm}
      // 删除普通任务中的rule参数
      if (params.taskType === '10') delete params.rule;

      if (params.pressureMode === '10') {
        params.pressureConfig = this.FormConcurrency;
        const { ladders, ...rest } = params.pressureConfig;
        params.pressureConfig = rest;
      } else if (params.pressureMode === '20') {
        params.pressureConfig = this.FormLadder;
        const { ...rest } = params.pressureConfig;
        params.pressureConfig = rest;
      }

      return params;
    },

    async clickUpdate() {
      this.$refs.ConfigRef.validate(async vaild => {
      // 判断是否验证通过，不通过则直接retrue
      if (!vaild) return;
      const params = this.dataSubmit()
      const response = await this.$api.updatePresetting(params.id,params);
      if (response.status === 200) {
        ElMessage({
          type: 'success',
          message: '修改成功',
          duration: 1000
       });
        this.closeDialog()
      }
      })
    },

    async clickAdd() {
      this.$refs.ConfigRef.validate(async vaild => {
      if (!vaild) return;

      const params = this.dataSubmit()

      const response = await this.$api.createPresetting(params);
      if (response.status === 201) {
        ElMessage({
          type: 'success',
          message: '添加成功',
          duration: 1000
        });
        this.closeDialog()
      }
      })
    },

    async popup(type, data) {
      this.dialogVisible = true;
      this.dialogType = type;
      if (type === 'add') {
        this.dialogTitle = '添加预设';
        this.configForm = {
          name: '',
          rule: '',
          taskType: this.taskType || '10',
          logMode: '0',
          pressureMode: '10',
          timeUnit: 's',
          control: '20',
          resource: '10',
          pressureConfig: {},
          project: this.pro.id,
          creator: this.username,
          thinkTimeType: '10',
          thinkTime: [0],
          master_server: null,
          worker_servers: [],
          distributed_mode: 'single',
        };
        this.FormConcurrency = {
          lastLong: '',
          concurrencyNumber: '',
          concurrencyStep: ''
        };
        this.FormLadder = {
          ladders: [
            { concurrencyNumber: '', concurrencyStep: '', lastLong: '' }
          ]
        };
        await this.getServerData();
      } else if (type === 'edit') {
        this.dialogTitle = '编辑预设';
        
        // 先获取服务器数据，确保选择框有数据源
        await this.getServerData();
        
        this.configForm = { ...data };
        
        // 处理服务器选择逻辑
        if (data.master_server || (data.worker_servers && data.worker_servers.length > 0)) {
          this.configForm.resource = '20'; // 切换到自定义模式
          this.configForm.master_server = data.master_server || null;
          this.configForm.worker_servers = data.worker_servers || [];
        }
        
        if (this.configForm.pressureMode === '10') {
          this.FormConcurrency = data.pressureConfig;
        } else if (this.configForm.pressureMode === '20') {
          this.FormLadder = data.pressureConfig;
        }
        
        this.$nextTick(() => {
          if (this.$refs.table) {
            this.$refs.table.toggleRowSelection(data, true);
          } else {
            console.error('table is undefined');
          }
        });
      }
    },

    handleSetData(data) {
      // 保留原有的运行模式，避免被覆盖
      const originalDistributedMode = this.configForm.distributed_mode;
      
      // 合并数据，但保留运行模式
      this.configForm = { ...data, distributed_mode: originalDistributedMode };
      
      // 如果导入的配置存在主服务器和工作服务器，自动切换到自定义模式
      if (data.master_server || (data.worker_servers && data.worker_servers.length > 0)) {
        this.configForm.resource = '20'; // 切换到自定义模式
        this.configForm.master_server = data.master_server || null;
        this.configForm.worker_servers = data.worker_servers || [];
      }
      
      if (this.configForm.pressureMode==='10') {
        this.FormConcurrency = data.pressureConfig
      }
      else if (this.configForm.pressureMode==='20') {
        this.FormLadder = data.pressureConfig
      }
    },

    async getServerData() {
      try {
        const response = await this.$api.getServers(this.pro.id, 1);
        if (response.status === 200) {
          this.serverData = response.data.result;
        }
      } catch (error) {
        console.error('加载服务器列表失败:', error);
        this.$message.error('加载服务器列表失败');
      }
    },



    closeDialog() {
      this.dialogVisible = false;
              this.configForm = {
                          name:'',
                          rule:'',
                          taskType: '10',
                          logMode: '0',
                          pressureMode: '10',
                          timeUnit: 's',
                          control:'20',
                          resource: '10',
                          pressureConfig:{},
                          project: '',
                          creator:'',
                          thinkTimeType: '10',
                          thinkTime:[0],
                          master_server: null,
                          worker_servers: [],
                          distributed_mode: 'single',
                        };
      this.FormConcurrency = {
                  lastLong:'',
                  concurrencyNumber:'',
                  concurrencyStep:''
      };
      this.FormLadder = {
        ladders: [
          { concurrencyNumber: '', concurrencyStep: '', lastLong: '' }
        ]
      };
      this.getPresetting(1);
    },

    async copyPresetting(data) {
      const params = {...data}
      params.name = params.name + '_副本'
      params.creator = this.username
      params.project = this.pro.id
      delete params.id
      delete params.update_time
      delete params.create_time

      const response = await this.$api.createPresetting(params);
      if (response.status === 201) {
        ElMessage({
          type: 'success',
          message: '复制成功',
          duration: 1000
        });
        this.closeDialog()
      }
    },
    addLadder() {
      this.FormLadder.ladders.push({
        concurrencyNumber: '',
        concurrencyStep: '',
        lastLong: ''
      });
      this.setRules()
    },

    setRules() {
      // 动态生成验证规则
      const ladderRules = {};
      // 遍历 FormLadder.ladders 数组，为每个阶梯项动态设置规则
      this.FormLadder.ladders.forEach((_, index) => {
        ladderRules[`ladders.${index}.concurrencyNumber`] = [
          { required: true, message: '并发用户数不能为空', trigger: 'blur' },
        ];
        ladderRules[`ladders.${index}.concurrencyStep`] = [
          { required: true, message: '并发数步长不能为空', trigger: 'blur' },
        ];
        ladderRules[`ladders.${index}.lastLong`] = [
          { required: true, message: '阶梯持续时长不能为空', trigger: 'blur' },
        ];
      });

      // 设置 rulesLadderMode 的值
      this.rulesLadderMode = ladderRules;
    },

    removeLadder(index) {
      if (this.FormLadder.ladders.length > 1) {
        this.FormLadder.ladders.splice(index, 1);
        this.setRules();
      }
    },

    onResourceChange() {
      if (this.configForm.resource === '10') {
        // 选择默认时，清空自定义服务器选择
        this.configForm.master_server = null;
        this.configForm.worker_servers = [];
      }
    },

    onDistributedModeChange() {
      if (this.configForm.distributed_mode === 'single') {
        this.configForm.resource = '10'; // 单机模式下，资源选择为默认
        this.configForm.master_server = null;
        this.configForm.worker_servers = [];
      }
    },

    getServerName(serverId) {
      if (!serverId || !this.serverData || this.serverData.length === 0) {
        return serverId;
      }
      const server = this.serverData.find(s => s.id === serverId);
      return server ? `${server.name} (${server.host_ip})` : serverId;
    },

    // 处理确认选择按钮点击事件
    handelSettingDlg() {
      if (!this.importSetData) {
        ElMessage({
          type: 'warning',
          message: '请先选择一个预设配置',
          duration: 2000
        });
        return;
      }

      // 通过事件向父组件传递选中的数据
      this.$emit('set-data', this.importSetData);
      
      // 关闭弹窗
      this.$emit('set-dlg', false);
      
      ElMessage({
        type: 'success',
        message: '配置导入成功',
        duration: 1000
      });
    },

    // 处理关闭窗口按钮点击事件
    handleClose() {
      this.$emit('set-dlg', false);
    }
  },

mounted() {this.setRules()},
created() {
    this.getPresetting(1)
    this.getServerData()
  }
}
</script>

<style scoped>
/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: white;
  border-radius: 12px;
  margin: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e9ecef;
}

.search-section {
  flex: 1;
  max-width: 400px;
}

.search-input {
  border-radius: 8px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid #e1e8ed;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper:hover) {
  border-color: #667eea;
  background: white;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.search-input :deep(.el-input__prefix) {
  color: #6c757d;
}

.action-section {
  display: flex;
  gap: 12px;
}

.action-btn {
  border-radius: 8px;
  font-weight: 500;
  padding: 10px 20px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.primary-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

/* 表格容器样式 */
.table-container {
  margin: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.custom-table {
  border-radius: 12px;
  position: relative;
  z-index: 1;
}

.custom-table :deep(.el-table__header) {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  z-index: 1;
}

.custom-table :deep(.el-table__header th) {
  background: transparent;
  color: #2c3e50;
  font-weight: 600;
  border-bottom: 2px solid #e1e8ed;
  z-index: 1;
}

.custom-table :deep(.el-table__fixed-header-wrapper) {
  z-index: 11;
}

.custom-table :deep(.el-table__fixed-header-wrapper .el-table__header) {
  z-index: 12;
}

.custom-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.custom-table :deep(.el-table__row:hover) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  transform: scale(1.01);
}

.custom-table :deep(.el-table__row td) {
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 8px;
}

/* 固定列样式 */
.custom-table :deep(.el-table__fixed) {
  z-index: 9;
}

.custom-table :deep(.el-table__fixed-right) {
  z-index: 9;
}

.custom-table :deep(.el-table__fixed-header-wrapper) {
  z-index: 20;
}

.custom-table :deep(.el-table__fixed-body-wrapper) {
  z-index: 8;
}

.custom-table :deep(.el-table__fixed-right-header-wrapper) {
  z-index: 20;
}

.custom-table :deep(.el-table__fixed-right-body-wrapper) {
  z-index: 8;
}

/* 确保固定表头内容在最上层 */
.custom-table :deep(.el-table__fixed-header-wrapper .el-table__header) {
  z-index: 21;
}

.custom-table :deep(.el-table__fixed-right-header-wrapper .el-table__header) {
  z-index: 21;
}

.custom-table :deep(.el-table__fixed-header-wrapper .el-table__header th) {
  z-index: 22;
}

.custom-table :deep(.el-table__fixed-right-header-wrapper .el-table__header th) {
  z-index: 22;
}

/* 确保表格容器有正确的层级 */
.table-container {
  position: relative;
  z-index: 1;
}

/* 强制固定列在最上层 */
.custom-table :deep(.el-table__fixed-right) {
  position: relative;
  z-index: 999 !important;
}

.custom-table :deep(.el-table__fixed-right-header-wrapper) {
  position: relative;
  z-index: 1000 !important;
}

.custom-table :deep(.el-table__fixed-right-header-wrapper .el-table__header) {
  position: relative;
  z-index: 1001 !important;
}

.custom-table :deep(.el-table__fixed-right-header-wrapper .el-table__header th) {
  position: relative;
  z-index: 1002 !important;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn-small {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  padding: 6px 12px;
}

.action-btn-small:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
  margin: 2px;
}

/* 分页器样式 */
.pagination-container {
  margin: 24px;
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.custom-pagination {
  background: white;
  padding: 16px 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.custom-pagination :deep(.el-pagination.is-background .el-pager li) {
  border-radius: 6px;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.custom-pagination :deep(.el-pagination.is-background .el-pager li:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.custom-pagination :deep(.el-pagination.is-background .el-pager li.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: right;
  margin-top: 20px;
  gap: 12px;
}

.form-container {
  display: flex;
  justify-content: space-between;
  gap: 24px;
}

.form-column {
  flex: 1;
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .search-section {
    max-width: 100%;
  }
  
  .action-section {
    justify-content: center;
  }
  
  .form-container {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}
</style>

<style>
/* 确保时间选择器弹窗在最上层 */
.el-time-panel, .el-picker-panel, .el-popper {
  z-index: 9999 !important;
}
</style>